import 'dart:async';

import 'package:connectivity/connectivity.dart';
import 'package:flutter/cupertino.dart';
import 'package:package_info/package_info.dart';

class InitAppModel with ChangeNotifier {
  // 版本号
  //String appVersion;

  // 网络状态
  bool networkstate = true;

  // 定时器
  static Timer _time;


  final Connectivity _c = Connectivity();
  StreamSubscription<ConnectivityResult> _connectivitySubscription;



  InitAppModel() {
    if(_time != null) {
      _time.cancel();
    }

    listenNetwork();
  }


  /// 读取操作系统、app版本号信息
  static Future<String> getPlatformInfo() async {
    // 获取当前app版本信息
    String version = (await PackageInfo.fromPlatform()).version;
    return version;
  }


  /// 侦听网络变化
  listenNetwork() {
    _connectivitySubscription = _c.onConnectivityChanged.listen((ConnectivityResult result) {
      //print(result.toString());
      if(result.toString() == "ConnectivityResult.none") {
        /**
         * 开启定时器防止wifi、移动网络时，其中任意一项中断会导致网络状态闪烁
         * 例：ture（正常）——false（中断）——true（正常）
         * 延时执行为确保网络连接的真实性
         */
        _time = Timer(Duration(seconds: 3), () {
          // 修改状态
          networkstate = false;

          // 通知网络变化
          notifyListeners();

          // 关闭定时器
          _time.cancel();
        });


      } else {

        if(_time != null) _time.cancel();

        // 修改状态
        networkstate = true;

        // 通知网络变化
        notifyListeners();
      }

    });
  }

  /// 关闭网络侦听
  closeNetworkListen() {
    _connectivitySubscription.cancel();
  }





}
